const categoryModel = require('../model/categoryModel')
const { SUCCESS_RESPONSE, FAIL_RESPONSE } = require('../config/constant')

// 获得分类名称数据
exports.getCategoryNameData = async (req, res) => {
  let result = await categoryModel.getCategoryName()
  res.json(SUCCESS_RESPONSE('获取分类名称数据成功', result))
}

// 修改数据
exports.changeCategoryData = async (req, res) => {
  let editData = req.body
  let { category_id, category_name } = editData
  // 检验是否重名
  let answer = await categoryModel.checkEditCategoryName(
    category_id,
    category_name
  )
  if (answer[0]) {
    res.json(FAIL_RESPONSE('00003', '分类名已存在，请更换一个'))
    return
  }
  let result = await categoryModel.changeCategory(editData)
  res.json(SUCCESS_RESPONSE('修改数据成功', result))
}

// 获取所编辑分类的数据
exports.getEditedCategoryData = async (req, res) => {
  let { category_id } = req.query
  let result = await categoryModel.getEditedCategory(category_id)
  res.json(SUCCESS_RESPONSE('获取所需编辑分类的数据成功', result[0]))
}

// 添加分类
exports.addCategoryData = async (req, res) => {
  let { category_name, intro, is_show, add_date, sort, admin_id } = req.body
  let answer = await categoryModel.checkCategoryName(category_name)

  if (answer.length > 0) {
    res.json(FAIL_RESPONSE('00002', '分类名已存在，请更换一个'))
    return
  }

  if (is_show === true) {
    is_show = 1
  } else {
    is_show = 0
  }
  categoryModel.addCategory(
    category_name,
    intro,
    is_show,
    add_date,
    sort,
    admin_id
  )
  res.json(SUCCESS_RESPONSE('添加分类成功'))
}

// 删除选中分类
exports.delSelectedData = (req, res) => {
  let { category_ids } = req.body
  categoryModel.delSelected(category_ids)
  res.json(SUCCESS_RESPONSE('删除选中分类成功'))
}

// 删除分类
exports.delCategoryData = (req, res) => {
  let { category_id } = req.body
  categoryModel.delCategory(category_id)
  res.json(SUCCESS_RESPONSE('删除分类成功'))
}

// 获取分类
exports.getCategoryData = async (req, res) => {
  let { page, pagesize, category_name, is_show, startDate, endDate } = req.query
  let result = await categoryModel.getCategory(
    page,
    pagesize,
    category_name,
    is_show,
    startDate,
    endDate
  )
  let count = await categoryModel.getCategoryCount(
    category_name,
    is_show,
    startDate,
    endDate
  )
  res.json(SUCCESS_RESPONSE('获取分类成功', { result, count }))
}
